// 预定义的颜色集合
const PREDEFINED_COLORS = [
  '#ff6b6b', '#4ecdc4', '#45b7d1', '#f9ca24', '#f0932b',
  '#eb4d4b', '#6c5ce7', '#fd79a8', '#fdcb6e', '#fd79a8',
  '#55efc4', '#81ecec', '#74b9ff', '#a29bfe', '#ffeaa7',
  '#fab1a0', '#e17055', '#636e72', '#ddd', '#b2bec3',
  '#00b894', '#00cec9', '#0984e3', '#6c5ce7', '#e84393',
  '#fd79a8', '#fdcb6e', '#e17055', '#74b9ff', '#a29bfe'
];

const getFixedColor = (index) => {
  return PREDEFINED_COLORS[index % PREDEFINED_COLORS.length];
};

// 优化的tooltip格式化函数，使用缓存
let tooltipCache = new Map();
const optimizedTooltipFormatter = (params) => {
  if (!params || params.length === 0) return '';
  const time = params[0].axisValue;
  const cacheKey = `${time}_${params.length}`;
  // 检查缓存
  if (tooltipCache.has(cacheKey)) {
    return tooltipCache.get(cacheKey);
  }
  const validData = params.filter(p => p.value !== null && p.value !== undefined && p.value !== '');
  if (validData.length === 0) {
    const result = `${time}<br/>暂无数据`;
    tooltipCache.set(cacheKey, result);
    return result;
  }
  let maxTemp = -Infinity;
  let minTemp = Infinity;
  let maxTempSeries = '';
  let minTempSeries = '';
  validData.forEach(item => {
    const temp = parseFloat(item.value);
    if (!isNaN(temp)) {
      if (temp > maxTemp) {
        maxTemp = temp;
        maxTempSeries = item.seriesName;
      }
      if (temp < minTemp) {
        minTemp = temp;
        minTempSeries = item.seriesName;
      }
    }
  });
  if (maxTemp === -Infinity || minTemp === Infinity) {
    const result = `${time}<br/>暂无有效数据`;
    tooltipCache.set(cacheKey, result);
    return result;
  }
  const result = `
    ${time}<br/>
    <span style="color: #ff6b6b;">●</span> 最高温度：${maxTemp}℃<br/>
    <span style="color: #ff6b6b;">●</span> 最高温度位置：${maxTempSeries}<br/>
    <span style="color: #4ecdc4;">●</span> 最低温度：${minTemp}℃<br/>
    <span style="color: #4ecdc4;">●</span> 最低温度位置：${minTempSeries}
  `;
  // 限制缓存大小
  if (tooltipCache.size > 100) {
    tooltipCache.clear();
  }
  tooltipCache.set(cacheKey, result);
  return result;
};

// 生成240个系列的配置，使用固定颜色
const generate240Series = () => {
  const series = [];
  for (let i = 0; i < 240; i++) {
    const color = getFixedColor(i);
    series.push({
      name: `电芯${i + 1}`,
      type: 'line',
      data: [],
      itemStyle: {
        color: color
      },
      lineStyle: {
        color: color,
        width: 1
      },
      symbol: 'none',
      smooth: false,
      showSymbol: false,
    });
  }
  return series;
};

export const getTemperatureDistributionOption = (timeAxisData = []) => {
  // 如果没有传入时间轴数据，生成默认的24小时数据
  if (!timeAxisData || timeAxisData.length === 0) {
    const generateTimeData = () => {
      const timeData = [];
      for (let hour = 0; hour < 24; hour++) {
        for (let minute = 0; minute < 60; minute += 1) { // 每1分钟一个点
          const timeStr = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
          timeData.push(timeStr);
        }
      }
      return timeData;
    };
    timeAxisData = generateTimeData();
  }

  return {
    title: {
      text: '单体温度趋势',
      textStyle: {
        fontSize: 16,
        color: '#fff'
      },
      left: 'center',
      top: 10,
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          show: false
        }
      },
      formatter: optimizedTooltipFormatter,
    },
    legend: {
      show: false
    },
    axisPointer: {
      link: [{ xAxisIndex: "all" }],
      label: {
        show: false
      }
    },
    grid: [
      {
        left: 60,
        right: '3%',
        top: 80,
        bottom: 60,
      }
    ],
    xAxis: [{
      type: 'category',
      data: timeAxisData,
      boundaryGap: false,
      axisLine: { onZero: true },
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      }
    }],
    yAxis: [
      {
        type: 'value',
        name: '温度(℃)',
        splitNumber: 5,
        nameTextStyle: {
          color: '#fff'
        },
        axisLabel: {
          color: '#fff'
        },
        axisLine: {
          lineStyle: {
            color: '#fff'
          }
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255,255,255,0.1)'
          }
        }
      }
    ],
    dataZoom: [
      {
        type: 'slider',
        show: true,
        xAxisIndex: [0],
        start: 0,
        end: 100, // 默认显示所有数据，240条线的温度趋势
        height: 20,
        bottom: 10,
        borderColor: '#ccc',
        fillerColor: 'rgba(167,183,204,0.4)',
        handleColor: '#fff',
        handleSize: '100%',
        textStyle: {
          color: '#fff'
        }
      },
      {
        type: 'inside',
        xAxisIndex: [0],
        start: 0,
        end: 20
      }
    ],
    series: generate240Series()
  };
};